package com.sfl.api_backend.controller.files;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sfl.api_backend.constant.HttpCode;
import com.sfl.api_backend.entity.Models;
import com.sfl.api_backend.service.IModelsService;
import com.sfl.api_backend.utils.Api.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

/**
 * <p>
 * 模型表 前端控制器
 * </p>
 *
 * @author szc
 * @since 2023-01-27
 */
@RestController
@RequestMapping("/files/models")
@Slf4j
public class ModelsController {

    @Resource
    public IModelsService modelsService;


    @PostMapping("/modify")
    @PreAuthorize("hasAuthority('User')")
    public RestResult modifly(@RequestBody Models vo) {
        // TODO: 不确定mybatis plus的updateById方法是否会自动忽略空值
        try {
            log.info("modifly model: {}", vo);
            modelsService.updateById(vo);
            return RestResult.success();
        }
        catch (Exception e) {
            log.error("modifly model: {} error", vo);
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('User')")
    public RestResult list(@RequestBody Models vo) {
        try {
            log.info("list models: {}", vo.getUserId());
            Wrapper<Models> wrapper = new LambdaQueryWrapper<Models>().eq(Models::getUserId, vo.getUserId()).or().eq(Models::getUserId,0);
            return RestResult.success(modelsService.list(wrapper));
        }
        catch (Exception e) {
            log.error("list models: {} error", vo.getUserId());
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/delect")
    @PreAuthorize("hasAuthority('User')")
    public RestResult delect(@RequestBody List<Integer> modelIds) {
        try {
            log.info("delect models: {}", modelIds);
            List<Models> models = modelsService.listByIds(modelIds);

            // 删除文件
            for(Models model : models){
                // remove file
                String path = model.getModelPath();
                File file = new File(path);
                if(file.exists()){
                    file.delete();
                }
            }

            return RestResult.success(modelsService.removeBatchByIds(modelIds));
        }
        catch (Exception e) {
            log.error("delect models: {} error", modelIds);
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

}
